//
//  UIViewController+Extension.swift
//  GXLSwiftTools
//
//  Created by HeHeAdmin on 2019/10/11.
//

import Foundation
import UIKit

//如何使用 ：https://github.com/linjieYang/NavigationGoBack
//1、自定义UINavigationController
//override func viewDidLoad() {
//    super.viewDidLoad()
//
//    // 强制开启侧滑返回操作
//    interactivePopGestureRecognizer?.delegate = self
//}
//2、在控制器里面
  /*
  override func navigationShouldPopMethod() -> Bool {
      print("执行返回操作四")
      goMeViewController();
      return false
  }
  
  func goMeViewController()  {
      
      // 1.动态获取命名空间
      guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String else{
      return;
      }
      // 2.根据字符串获取对应的Class并转成控制器的类型
      guard let className = NSClassFromString(nameSpace + "." + "NextVC")as? UIViewController.Type else{
      return
      }
      
  
      for item:UIViewController in self.navigationController!.viewControllers {
          
          if item.isKind(of:className) {
              self.navigationController?.popToViewController(item, animated: true);
          }
      }
  }
 
 */



/// 导航返回协议
@objc protocol NavigationProtocol {
    /// 导航将要返回方法
    ///
    /// - Returns: true: 返回上一界面， false: 禁止返回
    @objc optional func navigationShouldPopMethod() -> Bool
}

extension UIViewController: NavigationProtocol {
   open func navigationShouldPopMethod() -> Bool {
        return true
    }
}

extension UINavigationController: UINavigationBarDelegate, UIGestureRecognizerDelegate {
    
    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        if viewControllers.count < (navigationBar.items?.count)! {
            return true
        }
        var shouldPop = false
        let vc: UIViewController = topViewController!
        if vc.responds(to: #selector(navigationShouldPopMethod)) {
            shouldPop = vc.navigationShouldPopMethod()
        }
        if shouldPop {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            for subview in navigationBar.subviews {
                if 0.0 < subview.alpha && subview.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25) {
                        subview.alpha = 1.0
                    }
                }
            }
        }
        return false
    }
    
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if children.count == 1 {
            return false
        } else {
            if topViewController?.responds(to: #selector(navigationShouldPopMethod)) != nil {
                return topViewController!.navigationShouldPopMethod()
            }
            return true
        }
    }
}
